<?php

namespace AdminLogin\Controllers;

use Phalcon\Mvc\Controller;
use Forms\LoginForm;

class AdminLoginController extends Controller {

    public function loginAction() {
        $identity = $this->auth->getIdentity();
        if ($identity && ($identity['profile'] == '2' || $identity['profile'] == '3')) {
            return $this->response->redirect('admin');
        } else {
            $form = new LoginForm();
            if (!$this->request->isPost()) {

                if ($this->auth->hasRememberMe()) {
                    $this->auth->loginWithRememberMe();
                    return false;
                }
            } else {

                //valdate and print error in LoginForm function messages
                if ($form->isValid($this->request->getPost()) == true) {
                    try {
                        $this->auth->check(array(
                            'username' => $this->request->getPost('username'),
                            'password' => $this->request->getPost('password'),
                            'remember' => $this->request->getPost('remember'),
                        ));

                        if ($this->request->getQuery('url') == true) {
                            var_dump($this->request->getQuery('url'));
                            header('Location:' . $this->request->getQuery('url'));
                            return false;
                        }
                        return $this->response->redirect('admin');
                        /*                         * header('Location: index');
                          return false;* */
                    } catch (\Library\Exception $e) {
                        $form->appendMessage($e->getMessage(), "loginfail", null);
                    }
                }
            }
            $this->view->form = $form;
            $this->view->title = 'Admin Panel Login';
        }
    }

}
